import * as vscode from 'vscode';
import * as request from 'request-promise';

import { handleError, log } from '../log';
import { UserFriendlyError } from '../errors/user_friendly_error';
import { getUserAgentHeader } from '../utils/get_user_agent_header';
import { USER_COMMANDS } from '../command_names';

async function httpRequest() {

  const editor = vscode.window.activeTextEditor;
  if (editor) {
    const content = editor.document.getText();
    try{
      const userConfig = JSON.parse(content)
      const hmethod: string = userConfig?.http_method?.value || 'GET'

      const headers = userConfig?.header?.value || {
        "Content-Type": "application/json;charset=utf-8",
        ...getUserAgentHeader(),
      }
      const body = userConfig?.body?.value || {}
      const url = userConfig.url.value
      const proxy = userConfig.proxy.value

      await vscode.commands.executeCommand(USER_COMMANDS.SHOW_OUTPUT);
      const result = await fetch(url, hmethod, headers, body, proxy)
      log(`Response body:\n${result.response}`)

    }catch(err){
      handleError(
        new UserFriendlyError(
          'CSDN Workflow: 配置文件解析失败，点击查看详情',
          err
        ),
      );
    }
  }else{
    await vscode.window.showInformationMessage('CSDN Workflow: 未找到配置文件，请保持配置文件处于打开状态');
  }
}

async function showHttpConfig(): Promise<void> {
  // eslint-disable-next-line no-use-before-define
  const sampleText = httpConfig()
  const doc = await vscode.workspace.openTextDocument({ language: 'json', content: sampleText });
  await vscode.window.showTextDocument(doc);
}

async function fetch(url: string, method = 'GET', headers:Record<string, unknown>, data?: Record<string, unknown>, proxy?: string) {
  const config: request.RequestPromiseOptions = {
    method,
    headers
  };

  if (data) {
    config.formData = data;
  }

  if(proxy){
    config.proxy = proxy
  }

  config.transform = (body, response) => {
    try {
      return {
        response: body,
        headers: response.headers,
      };
    } catch (e) {
      handleError(
        new UserFriendlyError(
          'Failed to parse API response',
          e,
          `Response body: ${body}\nRequest URL: ${url}`,
        ),
      );
      return { error: e };
    }
  };

  return await request(url, config);
}

module.exports = {
  showHttpConfig,
  httpRequest
}

function httpConfig(): string {
  const config = {
    "note": "以下内容为 http 请求的临时配置文件，您可以直接进行编辑，我们会根据配置文件内容执行 http 请求。使用快捷键 shift+alt+r 运行。",
    "http_method": {
      "note": "请求方式，如：GET，POST，DELETE，PUT",
      "value": "GET"
    },
    "header": {
      "note": "http headers",
      "value": {
        "Content-Type": "application/json;charset=utf-8",
        ...getUserAgentHeader(),
      }
    },
    "body": {
      "note": "http body（选填）",
      "value": {}
    },
    "url": {
      "note": "请求地址",
      "value": "https://codechina.csdn.net/api/v4/templates/gitignores"
    },
    "proxy": {
      "note": "代理设置",
      "value": null
    }
  }
  return JSON.stringify(config, null, '\t')
}
